package com.cs.study.homework._0311;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {

        setAll(Person.class,"name","ls");

    }

        /** * * @param targetObj 要修改成员变量值的目标对象 *

         @param fieldName 对象中要修改的成员变量的名字

          * @param newValue 要修改成员变量值的新值 */

        public static void setAll(Object targetObj, String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
            // 获取字节码文件对象
            Class<?> aClass = Class.forName("com.cs.study.homework._0311.Person");
            Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
            Object o = declaredConstructor.newInstance();
            // 根据fieldName获取成员变量对象
            Field nameField = aClass.getDeclaredField("name");
            // 利用set方法修改成员变量的取值
            nameField.set(aClass,"ls");





        }
}
class Person{
    String name;
    int age;

    public Person() {
    }
}
